<template>
  <div class="video-page">
    <div class="main-content">
      <div class="video-info">
        <h1 class="video-title">{{ videoData.video_name }}</h1>
        <div class="video-stats">
          <span>{{ formatNumber(videoData.views) }} 次观看</span>
          <span>{{ formatNumber(videoData.likes) }} 赞</span>
          <span>{{ videoData.time }}</span>
        </div>
      </div>

      <div class="video-player">
        <vue3-video-play :src="videoData.url" :title="videoData.video_name" :width="playerWidth" :height="playerHeight"
          :autoplay="false" :loop="false" :muted="false" :controls="true" />
      </div>

      <div class="channel-info">
        <img :src="videoData.img" :alt="videoData.video_name" class="channel-avatar">
        <div class="channel-details">
          <h3>{{ videoData.person }}</h3>
          <p>{{ formatNumber(videoData.subscribe) }} 订阅者</p>
        </div>
        <button class="subscribe-button" :class="{ 'unsubscribe-button': isSubscribed }" @click="toggleSubscribe">
          {{ isSubscribed ? '取消订阅' : '订阅' }}
        </button>
        <button class="subscribe-button1" :class="{ 'unsubscribe-button': isCollected }" @click="toggleCollection">
          {{ isCollected ? '取消收藏' : '收藏' }}
        </button>
      </div>

      <div class="video-description">
        <p>{{ videoData.brief_introduction }}</p>
      </div>

      <div class="comments-section">
        <h2>评论 {{ commentCount }}</h2>
        <div class="comment-tabs">
          <button :class="{ active: activeTab === 'hot' }" @click="activeTab = 'hot'">热门</button>
          <button :class="{ active: activeTab === 'latest' }" @click="activeTab = 'latest'">最新</button>
        </div>

        <div class="comment-list">
          <div v-for="comment in comments" :key="comment.id" class="comment">
            <img :src="comment.avatar" :alt="comment.author" class="comment-avatar">
            <div class="comment-content">
              <div class="comment-header">
                <span class="comment-author">{{ comment.author }}</span>
                <span class="comment-date">{{ comment.date }}</span>
              </div>
              <p class="comment-text">{{ comment.text }}</p>
              <div class="comment-actions">
                <span>👍 {{ comment.likes }}</span>
                <span>回复</span>
              </div>
            </div>
          </div>
        </div>

        <button class="load-more-btn">查看更多评论</button>
      </div>
    </div>

    <div class="sidebar">
      <h3>相关推荐视频</h3>
      <div v-for="video in recommendedVideos" :key="video.id" class="recommended-video">
        <img :src="video.thumbnail" :alt="video.title" class="video-thumbnail">
        <div class="video-info">
          <h4>{{ video.title }}</h4>
          <p>{{ video.channelName }}</p>
          <p>{{ formatNumber(video.views) }} 次观看 · {{ video.publishedAgo }}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import vue3VideoPlay from 'vue3-video-play'
import 'vue3-video-play/dist/style.css'
import { useRouter } from 'vue-router'

const router = useRouter()

// 定义响应式数据来存储返回的视频数据
const videoData = ref({
  url: '',
  likes: 0,
  views: 0,
  category: '',
  time: '',
  person: '',
  subscribe: 0,
  img: '',
  video_id: 0,
  video_name: '',
  brief_introduction: ''
})

const videoTitle = ref('')
const views = ref(0)
const likes = ref(0)
const publishDate = ref('')
const videoUrl = ref('')
const activeTab = ref('hot')
const commentCount = ref(205174)

const playerWidth = ref('100%')
const playerHeight = ref('auto')

const channelName = ref('')
const channelAvatar = ref('')
const subscribers = ref(0)

const videoDescription = ref('')

const comments = ref([
  { id: 1, author: '茶鸟', avatar: 'https://s1.mintiny.com/wlake/i/2024/10/24/48hn.jpg', text: '原来只有一首歌吗，我还以为整张专辑都有😂（想太美', likes: 96387 },
  { id: 2, author: '中二小海豹', avatar: 'https://s1.mintiny.com/wlake/i/2024/10/24/14d2zf.jpg', date: '2022-07-06 12:08', text: '15号，快了。今天是小年，过几天就正式过年😽', likes: 9294 },
  { id: 3, author: '陈陈__陈陈', avatar: 'https://s1.mintiny.com/wlake/i/2024/10/24/14d60a.jpg', date: '2022-07-06 12:03', text: '15号才是整个专辑', likes: 1342 },
])

const recommendedVideos = ref([
  { id: 1, title: '【官方MV】Mojito - 周杰伦', thumbnail: 'https://s1.mintiny.com/wlake/i/05/6.jpg', channelName: '杰威尔音乐官方频道', views: 2740000, publishedAgo: '2年前' },
  { id: 2, title: '"卧槽！音乐一响，多少人的青春回来了！"', thumbnail: 'https://s1.mintiny.com/wlake/i/05/8.jpg', channelName: '百年影视馆', views: 4793000, publishedAgo: '1年前' },
  { id: 3, title: '用【青花瓷】演奏【青花瓷】', thumbnail: 'https://s1.mintiny.com/wlake/i/05/9.jpg', channelName: '白桦Bylin', views: 1281000, publishedAgo: '3个月前' },
])

const formatNumber = (num) => {
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + '万'
  }
  return num.toString()
}

const isSubscribed = ref(false) // 订阅状态
const isCollected = ref(false) // 收藏状态

const toggleSubscribe = () => {
  if (isSubscribed.value) {
    videoData.value.subscribe -= 1
    isSubscribed.value = false
  } else {
    videoData.value.subscribe += 1
    isSubscribed.value = true
  }
}

const toggleCollection = async () => {
  if (isCollected.value) {
    isCollected.value = false
  } else {
    try {
      const response = await fetch(`/addCollection?id=${videoData.value.video_id}`, {
        method: 'GET',
      });
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const data = await response.json();
      isCollected.value = true
    } catch (error) {
      console.error('Error adding collection:', error);
    }
  }
}

// 获取路由参数中的视频ID
const videoId = router.currentRoute.value.params.id

const addHistory = async () => {
  if (videoId) {
    try {
      const response = await fetch(`/addHistory?id=${videoId}`, {
        method: 'GET',
      });
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const data = await response.json();
      videoData.value = {
        url: data.url,
        likes: data.likes,
        views: data.views,
        category: data.category,
        time: data.time,
        person: data.person,
        subscribe: data.subscribe,
        img: data.img,
        video_id: data.video_id,
        video_name: data.video_name,
        brief_introduction: data.brief_introduction
      };
      videoTitle.value = data.video_name;
      views.value = data.views;
      likes.value = data.likes;
      publishDate.value = data.time;
      videoUrl.value = data.url;
      channelName.value = data.person;
      subscribers.value = data.subscribe;
      channelAvatar.value = data.img;
      videoDescription.value = data.brief_introduction;
      console.log('History added:', data);
    } catch (error) {
      console.error('Error adding history:', error);
    }
  }
};

// 在组件挂载时添加历史记录
onMounted(() => {
  addHistory()
})

const addCollection = async () => {
  if (videoId) {
    try {
      const response = await fetch(`/addCollection?id=${videoId}`, {
        method: 'GET',
      });
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const contentType = response.headers.get('content-type');
      if (!contentType || !contentType.includes('application/json')) {
        throw new Error('Invalid content type, expected application/json');
      }
      const data = await response.json();
      console.log('Collection added:', data);
      // 这里可以进行后续的数据更新操作
    } catch (error) {
      console.error('Error adding collection:', error);
    }
  }
};
</script>

<style scoped>
.video-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  display: flex;
}

.main-content {
  flex: 2;
  margin-right: 20px;
}

.video-title {
  font-size: 24px;
  margin-bottom: 10px;
}

.video-stats {
  color: #666;
  margin-bottom: 20px;
}

.video-stats span {
  margin-right: 15px;
}

.video-player {
  margin-bottom: 20px;
}

.channel-info {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.channel-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  margin-right: 10px;
}

.channel-details {
  flex-grow: 1;
}

.subscribe-button {
  background-color: #cc0000;
  color: white;
  border: none;
  padding: 10px 20px;
  cursor: pointer;
}

.subscribe-button1 {
  background-color: #007acc;
  color: white;
  border: none;
  padding: 10px 20px;
  cursor: pointer;
  margin-right: 10px;
}


.video-description {
  margin-bottom: 20px;
}

.comments-section {
  margin-top: 20px;
}

.comment-tabs {
  margin-bottom: 20px;
}

.comment-tabs button {
  background: none;
  border: none;
  cursor: pointer;
  margin-right: 15px;
  font-size: 16px;
}

.comment-tabs button.active {
  font-weight: bold;
}

.comment {
  display: flex;
  margin-bottom: 20px;
}

.comment-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.comment-content {
  flex-grow: 1;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.comment-author {
  font-weight: bold;
}

.comment-date {
  color: #666;
}

.comment-actions {
  margin-top: 5px;
}

.comment-actions span {
  margin-right: 15px;
  cursor: pointer;
}

.load-more-btn {
  width: 100%;
  padding: 10px;
  background-color: #f0f0f0;
  border: none;
  cursor: pointer;
  margin-top: 20px;
}

.sidebar {
  flex: 1;
}

.recommended-video {
  display: flex;
  margin-bottom: 20px;
}

.video-thumbnail {
  width: 120px;
  height: 80px;
  object-fit: cover;
  margin-right: 10px;
}

.recommended-video h4 {
  margin: 0 0 5px 0;
  font-size: 14px;
}

.recommended-video p {
  margin: 0;
  font-size: 12px;
  color: #666;
}
</style>